<?php

namespace App\Http\Controllers;

use App\Comment;
use App\Discuss;
use App\Http\Requests;
use App\Medal;
use App\Message;
use App\Parsedown;
use App\Task;
use App\Timeline;
use App\User;
use App\Utils;
use Auth;
use DB;
use Illuminate\Http\Request;
use Mail;
use View;

class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }


    public function ucenter(Request $request, $id)
    {
        Utils::log($request, 'profile');
        $id = Utils::url2id($id);
		$taskids = DB::select("select distinct(taskid) from solves where type=0 and userid=".$id);
        $taskidsStr = ""; 
        $ok = false;
        foreach($taskids as $k=>$v){
            if($ok) $taskidsStr .= ",";
            $taskidsStr .= $v->taskid;
            $ok = true;
        }   
      //  $jobs_cnt = DB::select("select count(*) as cc from jobs where taskid in (".$taskidsStr.")")[0]->cc;
	//	$jobs_cnt=0;

        $user = User::find($id);
        if ($user == null) return;
        $medals = Medal::whereUserid($id)->get();
        return View::make('users.ucenter')
            ->with(compact('user'))
            ->with(compact('medals'))
            ->with(compact('jobs_cnt'));
    }

    public function index(Request $request)
    {
        Utils::log($request, 'update');
        if ($request->isMethod('post')) {
            $input = $request->all();
			if(isset($input['avatar']) && strpos($input['avatar']->getMimeType(),"php")!=false)
			{
                $message = " 头像文件格式不对";
                return view::make("users.settings2", compact('message'));
			}
            $user = Auth::user();
            if (strlen($input['name']) > 25) {
                $message = " 名字太长太长啦";
                return view::make("users.settings2", compact('message'));
            } else if (strlen($input['name']) == 0) {
                $message = "名字不能为空";
                return view::make("users.settings2", compact('message'));
            } else if ($this->isUsernameExists($input)){
                $message = "这个名字已经有人使用啦";
                return view::make("users.settings2", compact('message'));
            }
            $user->name = $input['name'];
            $user->title = $input['title'];
            $user->introduce = $input['introduce'];
            $user->company = $input['company'];
            if (isset($input['avatar']))
                $user->avatar = $input['avatar'];
            $loc = $input['pro'] . "|" . $input['city'];
            $user->location = $loc;
            $user->save();
            $message = " 资料已更新";
            return view::make("users.settings2", compact('message'));
        }
        return view::make("users.settings2");
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function inbox(Request $request, $senderid = null, $receiverid=null)
    {
		$messages = null;
		if($senderid != null && $receiverid != null){
            $messages = Message::whereRaw("(senderid = ? and receiverid = ?) or (receiverid = ? and senderid = ?)", [Utils::url2id($senderid),
                Utils::url2id($receiverid), Utils::url2id($senderid), Utils::url2id($receiverid)])->orderby("created_at", "desc")->get();
            foreach ($messages as $k => $m) {
                if ($m['senderid'] == 1 || $m['senderid'] == 0) $messages[$k]['senderid'] = 55;
            }
        }
        else {
            Utils::log($request, 'inbox');
            //
            $user = Auth::user();
            $user->msgcnt = 0;
            $user->save();
            $messages = Auth::user()->messages()->recent()->get();

            // Replace admin to user 55
            foreach ($messages as $k => $m) {
                if ($m['senderid'] == 1 || $m['senderid'] == 0) $messages[$k]['senderid'] = 55;
            }
        }

        return view('users.inbox', compact('messages'));
    }

    public function getUserTasks(Request $request)
    {
        //select * from tasks where contributor=2199;
        $id = $request->all()['userid'];
        $data = Task::whereContributor($id)->orderBy("created_at", "desc")->get();
        foreach ($data as $k => $v) {
            $data[$k]['url'] = Utils::id2url($data[$k]['id']);
            //$data[$k]['user'] = User::find($id);
			$data[$k]['answer']="null";
        }
        return response()->json($data);
    }

    public function getUserKuibu(Request $request)
    {
        $ans = array();
        for ($i = 0; $i < 4; $i++) {
            $arr = array();
            $arr['time'] = "2014-01-01 11:11:11";
            $arr['type'] = "贡献题目";
            $arr['num'] = "400";
            $arr['text'] = "因为贡献了码之初";
            $ans[] = $arr;
        }
        return response()->json($ans);
    }

    public function getUserStudies(Request $request)
    {
        $id = $request->all()['userid'];
        $user = User::find($id);
        $data = Comment::whereRaw("userid = ? and type=1 and `delete`=0", [$id])->orderBy("created_at", "desc")->get();
        $ans = array();
        foreach ($data as $k => $v) {
            $Parsedown = new Parsedown();
            $data[$k]->content = $Parsedown->text($v->comment);
            $data[$k]['q'] = Discuss::find($v->taskid);
            if ($data[$k]['q'] == null) continue;
            $data[$k]['q']['url'] = Utils::id2url($data[$k]['q']['id']);
            $data[$k]['url'] = Utils::id2url($data[$k]['id']);
            $data[$k]['username'] = $user->name;
            $ans[] = $data[$k];
        }
        return response()->json($ans);
    }

    public function getUserDiscusses(Request $request)
    {
        $id = $request->all()['userid'];
        $user = User::find($id);
        $data = Discuss::whereRaw("userid = ?	and `delete`=0", [$id])->orderBy("created_at", "desc")->get();
        foreach ($data as $k => $v) {
            $Parsedown = new Parsedown();
            $data[$k]->content = $Parsedown->text($v->content);
            $data[$k]['url'] = Utils::id2url($data[$k]['id']);
            $data[$k]['username'] = $user->name;
        }
        return response()->json($data);
    }

    public function getUsertimeline(Request $request)
    {
        $id = $request->all()['userid'];
        $page = $request->all()['page'];
        $num = 15;
        $data = Timeline::whereRaw("userid = ? and type=1", [$id])->orderBy("timestamp", "desc")->skip($num * ($page - 1))->take($num)->get();
        return response()->json($data);
    }

    public function sendMsg(Request $request)
    {
        $input = $request->all();
        $data = array();
        $data['senderid'] = Auth::user()->id;
        $user = User::find($input['userid']);
        $user->msgcnt += 1;
        $user->save();
        $data['receiverid'] = $user->id;
        $data['content'] = $input['content'];
        Message::create($data);
        $arr = array();
        $arr['success'] = true;
        return response()->json($arr);
    }

    public function sendmail(Request $request)
    {
        $user = Auth::user();
        $url = md5("ql_" . $user->id . "_coder");
        Mail::send('emails.welcome', ['url' => $url, 'name' => $user->name], function ($message) use ($user) {
            $message->to($user->email, 'oreo')->subject('[千里码]邮箱激活');
        });
        return "1";
    }

    public function active(Request $request, $id)
    {
        $url = md5("ql_" . Auth::user()->id . "_coder");
        if ($url == $id) {
            Auth::user()->active = 1;
            Auth::User()->save();
        } else {
            echo "异常的参数";
            die;
        }
        return view::make("users.active");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        $user = User::find(Auth::user()->id);
        $input = $request->all();
        $user->avatar = $input['avatar'];
        $user->save();
        echo '<img src="' . $user->avatar->url() . '" >';
        echo '<img src="' . $user->avatar->url('medium') . '" >';
        echo '<img src="' . $user->avatar->url('thumb') . '" >';
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request $request
     * @param  int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * @param $input
     * @return bool
     */
    private function isUsernameExists($input)
    {
        $originalName = User::find(Auth::user()->id)['name'];
        if ($originalName === $input['name']) {
            return false;
        }
        return count(User::where("name", $input['name'])->take(1)->get()) > 0;
    }
}
